import * as vscode from 'vscode';

export async function startDebugOnCppExecutable(nodeName: string, packageName: string, args: string[]) {
    const debugConfiguration: vscode.DebugConfiguration = {
        name: `ROS2:Debug:${nodeName}`,
        type: 'cppdbg',
        request: 'launch',
        program: `\${workspaceFolder}/install/${packageName}/lib/${packageName}/${nodeName}`,
        args: args,
        stopAtEntry: false,
        cwd: '${workspaceFolder}',
        environment: [],
        externalConsole: false,
        MIMode: 'gdb',
        setupCommands: [
            {
                description: 'Enable pretty-printing for gdb',
                text: '-enable-pretty-printing',
                ignoreFailures: true
            }
        ],
        //preLaunchTask: 'start_ros2_node',
        miDebuggerPath: '/usr/bin/gdb',
        justMyCode: true,
    };
    await startDebug(debugConfiguration);
}

export async function startDebugOnPythonExecutable(nodeName: string, packageName: string, args: string[]) {
    const debugConfiguration: vscode.DebugConfiguration = {
        name: `ROS2:Debug:${nodeName}`,
        type: 'debugpy',
        request: 'launch',
        program: `\${workspaceFolder}/install/${packageName}/lib/${packageName}/${nodeName}`,
        args: args,
        cwd: '${workspaceFolder}',
        environment: [],
        console: "integratedTerminal",
        justMyCode: true,
    };
    await startDebug(debugConfiguration);
}

export async function startDebugOnLaunchFile(launchFile: string, packageName: string, args: string[]) {
    const debugConfiguration: vscode.DebugConfiguration = {
        name: `ROS2:Debug:${launchFile}`,
        type: 'ros',
        request: 'launch',
        target: `\${workspaceFolder}/install/${packageName}/share/${packageName}/launch/${launchFile}`,
        args: args,
        cwd: '${workspaceFolder}',
        environment: [],
        console: "integratedTerminal",
        justMyCode: true,
    };
    await startDebug(debugConfiguration);
}

async function startDebug(config: vscode.DebugConfiguration) {
    const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
    if (!workspaceFolder) {
        vscode.window.showErrorMessage('No workspace folder found.');
        return;
    }
    await vscode.debug.startDebugging(workspaceFolder, config);
}